import { dumpPathCache, logDataCache } from '../utils/cacheManager'
import { useDumpStore } from '../stores/dumps'
import { useFileDataStore } from '../stores/fileData'
import { getDumpLogData } from '../utils/archiveDb'

// 转储文件信息接口
export interface DumpFileInfo {
  path: string
  size: number
  extracted: boolean
  included: boolean
  lastModified: number
  type: 'framework' | 'operation' | 'app'
  index: number
}

// 转储数据缓存项
export interface DumpDataCacheItem {
  workspaceId: string
  dumpType: 'framework' | 'operation' | 'app'
  index: number
  data: string
  size: number
  timestamp: number
  compressed: boolean
}

// 转储缓存统计
export interface DumpCacheStats {
  totalFiles: number
  cachedFiles: number
  totalSize: number
  cachedSize: number
  hitRate: number
  lastUpdate: number
}

/**
 * 转储文件缓存服务
 * 专门管理转储文件路径和数据的缓存
 */
export class DumpCacheService {
  private _dumpStore: any = null
  private _fileDataStore: any = null
  private pathScanCache = new Map<string, DumpFileInfo[]>()
  private extractionPromises = new Map<string, Promise<string | null>>()
  private lastScanTime = new Map<string, number>()
  private scanCooldown = 5000 // 5秒扫描冷却时间

  private get dumpStore() {
    if (!this._dumpStore) {
      this._dumpStore = useDumpStore()
    }
    return this._dumpStore
  }

  private get fileDataStore() {
    if (!this._fileDataStore) {
      this._fileDataStore = useFileDataStore()
    }
    return this._fileDataStore
  }

  constructor() {
    this.initializeDumpCache()
  }

  /**
   * 初始化转储缓存
   */
  private async initializeDumpCache(): Promise<void> {
    console.log('[DumpCache] 初始化转储缓存服务')
    
    try {
      // 从持久化存储恢复转储路径缓存
      await dumpPathCache.warmup(() => Promise.resolve({}))
      console.log('[DumpCache] 转储路径缓存预热完成')
    } catch (error) {
      console.error('[DumpCache] 初始化转储缓存失败:', error)
    }
  }

  /**
   * 扫描工作区的转储文件
   */
  async scanDumpFiles(workspaceId: string, forceRefresh: boolean = false): Promise<DumpFileInfo[]> {
    const cacheKey = `dump_files_${workspaceId}`
    const now = Date.now()
    
    // 检查扫描冷却时间
    const lastScan = this.lastScanTime.get(workspaceId) || 0
    if (!forceRefresh && (now - lastScan) < this.scanCooldown) {
      const cached = this.pathScanCache.get(workspaceId)
      if (cached) {
        console.log(`[DumpCache] 使用缓存的转储文件列表: ${workspaceId}`)
        return cached
      }
    }

    // 检查持久化缓存
    if (!forceRefresh) {
      const persistedFiles = dumpPathCache.get<DumpFileInfo[]>(cacheKey)
      if (persistedFiles) {
        console.log(`[DumpCache] 从持久化缓存获取转储文件: ${workspaceId}`)
        this.pathScanCache.set(workspaceId, persistedFiles)
        return persistedFiles
      }
    }

    console.log(`[DumpCache] 扫描工作区转储文件: ${workspaceId}`)
    
    try {
      const fileData = this.fileDataStore.getFileData(workspaceId)
      if (!fileData) {
        console.warn(`[DumpCache] 工作区文件数据不存在: ${workspaceId}`)
        return []
      }

      const dumpFiles = await this.extractDumpFilesFromData(fileData, workspaceId)
      
      // 缓存结果
      this.pathScanCache.set(workspaceId, dumpFiles)
      this.lastScanTime.set(workspaceId, now)
      
      // 持久化缓存
      dumpPathCache.set(cacheKey, dumpFiles, { persist: true })
      
      console.log(`[DumpCache] 扫描完成，发现 ${dumpFiles.length} 个转储文件`)
      return dumpFiles
      
    } catch (error) {
      console.error(`[DumpCache] 扫描转储文件失败: ${workspaceId}`, error)
      return []
    }
  }

  /**
   * 从文件数据中提取转储文件信息
   */
  private async extractDumpFilesFromData(fileData: string, workspaceId: string): Promise<DumpFileInfo[]> {
    const dumpFiles: DumpFileInfo[] = []
    const lines = fileData.split('\n')
    
    // 转储文件路径模式
    const dumpPatterns = {
      framework: /dump_info\/LogDump\/framework\.(\d+)\.gz/,
      operation: /dump_info\/LogDump\/operation\.(\d+)\.gz/,
      app: /dump_info\/LogDump\/app\.(\d+)\.gz/
    }

    for (const line of lines) {
      // 检查每种转储类型
      for (const [type, pattern] of Object.entries(dumpPatterns)) {
        const match = line.match(pattern)
        if (match) {
          const index = parseInt(match[1])
          const path = match[0]
          
          // 提取文件大小（如果可用）
          const sizeMatch = line.match(/(\d+)\s+bytes?/)
          const size = sizeMatch ? parseInt(sizeMatch[1]) : 0
          
          // 检查是否已包含在分析中
          const included = this.dumpStore.isDumpIncluded(
            workspaceId, 
            type === 'app' ? 'debug' : type as 'framework' | 'operation', 
            path
          )
          
          dumpFiles.push({
            path,
            size,
            extracted: true, // 假设已解压
            included,
            lastModified: Date.now(),
            type: type as 'framework' | 'operation' | 'app',
            index
          })
        }
      }
    }

    // 按类型和索引排序
    dumpFiles.sort((a, b) => {
      if (a.type !== b.type) {
        return a.type.localeCompare(b.type)
      }
      return a.index - b.index
    })

    return dumpFiles
  }

  /**
   * 获取转储文件数据
   */
  async getDumpData(workspaceId: string, dumpType: 'framework' | 'operation' | 'app', index: number): Promise<string | null> {
    const cacheKey = `dump_data_${workspaceId}_${dumpType}_${index}`
    
    // 检查缓存
    const cached = logDataCache.get<DumpDataCacheItem>(cacheKey)
    if (cached) {
      console.log(`[DumpCache] 从缓存获取转储数据: ${dumpType}.${index}`)
      return cached.data
    }

    // 检查是否正在提取
    const extractionKey = `${workspaceId}_${dumpType}_${index}`
    if (this.extractionPromises.has(extractionKey)) {
      console.log(`[DumpCache] 等待转储数据提取: ${dumpType}.${index}`)
      return await this.extractionPromises.get(extractionKey)!
    }

    // 开始提取数据
    const extractionPromise = this.extractDumpData(workspaceId, dumpType, index)
    this.extractionPromises.set(extractionKey, extractionPromise)

    try {
      const data = await extractionPromise
      
      if (data) {
        // 缓存数据
        const cacheItem: DumpDataCacheItem = {
          workspaceId,
          dumpType,
          index,
          data,
          size: data.length,
          timestamp: Date.now(),
          compressed: false
        }
        
        logDataCache.set(cacheKey, cacheItem, { persist: true })
        console.log(`[DumpCache] 转储数据已缓存: ${dumpType}.${index}, 大小: ${(data.length / 1024).toFixed(2)}KB`)
      }
      
      return data
    } finally {
      this.extractionPromises.delete(extractionKey)
    }
  }

  /**
   * 提取转储数据
   */
  private async extractDumpData(workspaceId: string, dumpType: 'framework' | 'operation' | 'app', index: number): Promise<string | null> {
    try {
      console.log(`[DumpCache] 开始提取转储数据: ${dumpType}.${index}`)
      
      const data = await getDumpLogData(workspaceId, dumpType, index)
      
      if (data) {
        console.log(`[DumpCache] 转储数据提取完成: ${dumpType}.${index}, 大小: ${(data.length / 1024).toFixed(2)}KB`)
        return data
      } else {
        console.warn(`[DumpCache] 转储数据为空: ${dumpType}.${index}`)
        return null
      }
    } catch (error) {
      console.error(`[DumpCache] 提取转储数据失败: ${dumpType}.${index}`, error)
      return null
    }
  }

  /**
   * 预加载转储数据
   */
  async preloadDumpData(workspaceId: string, dumpType: 'framework' | 'operation' | 'app', maxFiles: number = 5): Promise<void> {
    console.log(`[DumpCache] 开始预加载 ${dumpType} 转储数据，最多 ${maxFiles} 个文件`)
    
    try {
      // 获取包含的转储文件
      const dumpFiles = await this.scanDumpFiles(workspaceId)
      const targetFiles = dumpFiles
        .filter(file => file.type === dumpType && file.included)
        .slice(0, maxFiles) // 限制预加载数量
      
      if (targetFiles.length === 0) {
        console.log(`[DumpCache] 没有需要预加载的 ${dumpType} 转储文件`)
        return
      }

      // 并行预加载（限制并发数）
      const concurrency = 3
      const chunks = this.chunkArray(targetFiles, concurrency)
      
      for (const chunk of chunks) {
        const loadTasks = chunk.map(file => 
          this.getDumpData(workspaceId, file.type, file.index)
        )
        
        await Promise.allSettled(loadTasks)
        
        // 稍作延迟，避免阻塞
        await new Promise(resolve => setTimeout(resolve, 100))
      }
      
      console.log(`[DumpCache] ${dumpType} 转储数据预加载完成，处理了 ${targetFiles.length} 个文件`)
      
    } catch (error) {
      console.error(`[DumpCache] 预加载 ${dumpType} 转储数据失败:`, error)
    }
  }

  /**
   * 批量预加载所有类型的转储数据
   */
  async preloadAllDumpData(workspaceId: string): Promise<void> {
    console.log(`[DumpCache] 开始批量预加载所有转储数据: ${workspaceId}`)
    
    const dumpTypes: ('framework' | 'operation' | 'app')[] = ['framework', 'operation', 'app']
    
    for (const dumpType of dumpTypes) {
      try {
        await this.preloadDumpData(workspaceId, dumpType)
        
        // 类型之间稍作延迟
        await new Promise(resolve => setTimeout(resolve, 500))
      } catch (error) {
        console.error(`[DumpCache] 预加载 ${dumpType} 失败:`, error)
      }
    }
    
    console.log(`[DumpCache] 所有转储数据预加载完成: ${workspaceId}`)
  }

  /**
   * 更新转储文件包含状态
   */
  updateDumpInclusionStatus(workspaceId: string, dumpType: 'framework' | 'operation' | 'debug', path: string, included: boolean): void {
    console.log(`[DumpCache] 更新转储文件包含状态: ${path} -> ${included}`)
    
    // 更新内存缓存
    const cachedFiles = this.pathScanCache.get(workspaceId)
    if (cachedFiles) {
      const file = cachedFiles.find(f => f.path === path)
      if (file) {
        file.included = included
        file.lastModified = Date.now()
        
        // 更新持久化缓存
        const cacheKey = `dump_files_${workspaceId}`
        dumpPathCache.set(cacheKey, cachedFiles, { persist: true })
      }
    }
    
    // 如果文件被包含，预加载其数据
    if (included) {
      const indexMatch = path.match(/\.(\d+)\.gz$/)
      if (indexMatch) {
        const index = parseInt(indexMatch[1])
        const actualType = dumpType === 'debug' ? 'app' : dumpType
        
        // 异步预加载
        setTimeout(() => {
          this.getDumpData(workspaceId, actualType as 'framework' | 'operation' | 'app', index)
        }, 100)
      }
    }
  }

  /**
   * 清理工作区转储缓存
   */
  clearWorkspaceDumpCache(workspaceId: string): void {
    console.log(`[DumpCache] 清理工作区转储缓存: ${workspaceId}`)
    
    // 清理内存缓存
    this.pathScanCache.delete(workspaceId)
    this.lastScanTime.delete(workspaceId)
    
    // 清理持久化缓存中的相关项
    const patterns = [
      `dump_files_${workspaceId}`,
      `dump_data_${workspaceId}_`
    ]
    
    // 这里需要实现按模式删除的功能
    // 暂时记录需要清理的模式
    console.log(`[DumpCache] 需要清理的缓存模式:`, patterns)
  }

  /**
   * 获取转储缓存统计信息
   */
  getDumpCacheStats(workspaceId?: string): DumpCacheStats {
    let totalFiles = 0
    let cachedFiles = 0
    let totalSize = 0
    let cachedSize = 0
    
    if (workspaceId) {
      // 特定工作区的统计
      const files = this.pathScanCache.get(workspaceId) || []
      totalFiles = files.length
      
      files.forEach(file => {
        totalSize += file.size
        
        const cacheKey = `dump_data_${workspaceId}_${file.type}_${file.index}`
        if (logDataCache.has(cacheKey)) {
          cachedFiles++
          const cached = logDataCache.get<DumpDataCacheItem>(cacheKey)
          if (cached) {
            cachedSize += cached.size
          }
        }
      })
    } else {
      // 全局统计
      this.pathScanCache.forEach((files, wsId) => {
        totalFiles += files.length
        
        files.forEach(file => {
          totalSize += file.size
          
          const cacheKey = `dump_data_${wsId}_${file.type}_${file.index}`
          if (logDataCache.has(cacheKey)) {
            cachedFiles++
            const cached = logDataCache.get<DumpDataCacheItem>(cacheKey)
            if (cached) {
              cachedSize += cached.size
            }
          }
        })
      })
    }
    
    const hitRate = totalFiles > 0 ? (cachedFiles / totalFiles) * 100 : 0
    
    return {
      totalFiles,
      cachedFiles,
      totalSize,
      cachedSize,
      hitRate,
      lastUpdate: Date.now()
    }
  }

  /**
   * 获取转储文件列表（按类型）
   */
  async getDumpFilesByType(workspaceId: string, dumpType: 'framework' | 'operation' | 'app'): Promise<DumpFileInfo[]> {
    const allFiles = await this.scanDumpFiles(workspaceId)
    return allFiles.filter(file => file.type === dumpType)
  }

  /**
   * 检查转储数据是否已缓存
   */
  isDumpDataCached(workspaceId: string, dumpType: 'framework' | 'operation' | 'app', index: number): boolean {
    const cacheKey = `dump_data_${workspaceId}_${dumpType}_${index}`
    return logDataCache.has(cacheKey)
  }

  /**
   * 获取缓存的转储数据大小
   */
  getCachedDumpDataSize(workspaceId: string, dumpType: 'framework' | 'operation' | 'app', index: number): number {
    const cacheKey = `dump_data_${workspaceId}_${dumpType}_${index}`
    const cached = logDataCache.get<DumpDataCacheItem>(cacheKey)
    return cached ? cached.size : 0
  }

  /**
   * 强制刷新转储文件扫描
   */
  async refreshDumpFiles(workspaceId: string): Promise<DumpFileInfo[]> {
    console.log(`[DumpCache] 强制刷新转储文件扫描: ${workspaceId}`)
    return await this.scanDumpFiles(workspaceId, true)
  }

  /**
   * 工具方法：将数组分块
   */
  private chunkArray<T>(array: T[], chunkSize: number): T[][] {
    const chunks: T[][] = []
    for (let i = 0; i < array.length; i += chunkSize) {
      chunks.push(array.slice(i, i + chunkSize))
    }
    return chunks
  }

  /**
   * 销毁服务
   */
  destroy(): void {
    this.pathScanCache.clear()
    this.extractionPromises.clear()
    this.lastScanTime.clear()
    console.log('[DumpCache] 转储缓存服务已销毁')
  }
}

// 全局转储缓存服务实例
export const dumpCacheService = new DumpCacheService()